<template>
	<div class="login-container">
		<div class="form-wrapper">
			<div class="header-img"></div>
			<el-form :model="loginForm" :rules="loginRules" ref="loginRef">
				<el-form-item prop="mobile">
					<el-input v-model="loginForm.mobile" placeholder="请输入手机号"></el-input>
				</el-form-item>
				<el-form-item prop="code">
					<el-input v-model="loginForm.code" placeholder="请输入验证码"></el-input>
				</el-form-item>
				<el-form-item prop="agree">
					<el-checkbox v-model="loginForm.agree">我已阅读并同意用户协议和隐私条款</el-checkbox>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="onLogin" class="login-btn" :loading="loginLoading">立即登录</el-button>
				</el-form-item>
			</el-form>
		</div>
	</div>
</template>

<script>
	import { login } from '@/api/user.js'
	export default {
		name: 'LoginIndex',
		data () {
			// 手机自定义验证规则
			var checkMobile = (rule, value, callback) => {
				// 正则表达式语法
				const regMobile = /^1[3|4|5|7|8][0-9]{9}$/
				if (regMobile.test(value)) {
					return callback()
				} else {
					callback(new Error('验证不通过,请输入合法的手机号码!'))
				}
			}
			// 阅读隐私条款
			var checkAgree = (rule, value, callback) => {
				// 正则表达式语法
				if (value) {
					return callback()
				} else {
					callback(new Error('请同意用户协议！'))
				}
			}
			return {
				// 登录表单对象
				loginForm: {
					mobile: '13911111111',
					code: '246810',
					// 是否同意条款
					agree: false
				},
				// 登录表单验证规则对象
				loginRules: {
					mobile: [
					 { validator: checkMobile, trigger: 'change' }
					],
					code: [
					 { required: true, message: '请输入验证码', trigger: 'change' },
					 { min: 4, max: 6, message: '长度在4~6个字符', trigger: 'blur' }
					],
					agree: [
						{ validator: checkAgree, trigger: 'change' }
					]
				},
				// 默认状态
				loginLoading: false
			}
		},
		methods: {
			// 登录
			onLogin () {
				// 获取表单数据
				// 表单验证
				this.$refs.loginRef.validate(valid => {
					if (!valid) return
					this.loginLoading = true

					// 验证通过,提交登录
					login(this.loginForm).then(({ data: res }) => {
						this.$message.success('登录成功！')
						this.loginLoading = false
						window.sessionStorage.setItem('token', res.data.token)
						this.$router.push('/home')
					}).catch(err => {
						this.$message.error('登录失败：' + err)
						this.loginLoading = false
					})
				})
			}
		}
	}
</script>
<style lang="less" scoped>
	.login-container {
		position: fixed;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		display: flex;
		align-items: center;
		justify-content: center;
		background: url(./images/login_bg.jpg) no-repeat;
		background-size: cover;

		.form-wrapper {
			background-color: #fff;
			padding: 20px 50px;
			min-width: 320px;

			.header-img {
				margin: 22px auto;
				width: 150px;
				height: 33px;
				background: url(images/logo_index.png) no-repeat;
				background-size: 150px 33px;
			}

			.login-btn {
				width: 100%;
			}
		}
	}
</style>
